/* Archive Extractor
 * Copyright 2008-2009 Matthew Hoops
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $URL: http://archive-extractor.googlecode.com/svn/trunk/gzip.cpp $
 * $Id: gzip.cpp 2 2009-03-23 01:29:43Z clone2727 $
 *
 */

#include "gzip.h"

GZipArchive::GZipArchive() : Archive() {
}

std::vector<const char*> GZipArchive::getArchiveExtensions() {
	std::vector<const char*> exList;
	exList.push_back("gz");
	exList.push_back("tgz"); // This is a tarball (really tar.gz)
	return exList;
}

int GZipArchive::detect(const char* filename) {
	// First, let's do our own check of the header.
	FILE* file = fopen(filename, "rb");
	uint16 tag = readUint16BE(file);
	fclose(file);
	if (tag != 0x1f8b)
		return 0;

	// Now, let's try to open it via zlib's interface.
	_handle = gzopen(filename, "rb");
	if (_handle)
		return 100;
		
	return 0;
}

// Read data in chunks of 16384 bytes at a time
#define GZIP_CHUNK_SIZE 16384

bool GZipArchive::extractFiles(const char* filename) {
	const char* outputFileName = genOutFileName(filename);
	printf ("Extracting file \'%s\'...\n", outputFileName);
	
	FILE* output = fopen(outputFileName, "wb");

	// Read data in chunks of GZIP_CHUNK_SIZE
	while (!gzeof(_handle)) {
		byte *data = (byte *)malloc(GZIP_CHUNK_SIZE);
		uint32 actualSize = gzread(_handle, data, GZIP_CHUNK_SIZE);
		fwrite(data, 1, actualSize, output);
		free(data);
	}
	
	fflush(output);
	fclose(output);
	
	gzclose(_handle);

	return true;
}

const char* GZipArchive::genOutFileName(const char* filename) {
	return "gzip_temp.tar"; // TODO
}
